package com.king.designpatterns.hybriddesignpattern.hybriddesignpattern.observingtheintermediarypatterns;

import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

/**
 * 事件分发器(事件观察者)
 *
 * @author king
 * @date 2021-06-15 13:51
 */
public class EventDispatch implements Observer {

    // 单例模式
    private static EventDispatch dispatch = new EventDispatch();

    // 事件处理者
    private Vector<EventCustomer> customers = new Vector<>();

    private EventDispatch() {
    }

    public static EventDispatch getEventDispatch() {
        return dispatch;
    }

    @Override
    public void update(Observable o, Object arg) {
        Product p = (Product) arg;
        // 事件
        ProductEvent event = (ProductEvent) o;
        // 处理者处理事件，中介者模式的核心
        for (EventCustomer e : customers) {
            for (ProductEventType t : e.getCustomType()) {
                if (t.getValue() == event.getType().getValue()){
                    e.exec(event);
                }
            }
        }
    }

    // 注册事件处理者
    public void registerCustomer(EventCustomer customer){
        customers.add(customer);
    }
}
